import eventSettings from "../utils/eventSettings";
import { location } from "../utils/getLocation";
import settings from "../utils/settings";
import { clearTabCompletionMessage, MessageID, partylist, stripRank } from "../utils/utils";

//Auto Accept Party Invite
export let AutoAcceptParty = {
    all : false,
    players:{},
    add(player="",time=0) {
        if(player) this.players[player.toLowerCase()] = (time ? Date.now() + time * 1000 : 0);
        else this.all = true;
    }
}

function acceptparty(p1){
    if(AutoAcceptParty.all){
        ChatLib.chat("§6§l[BZA] §b已帮您自动接受队伍邀请");
        ChatLib.command(`p accept ${p1}`);
        AutoAcceptParty.all = false;
        return true;
    } else {
        p1 = p1.toLowerCase();
        if(AutoAcceptParty.players[p1] != undefined) {
            if(AutoAcceptParty.players[p1] === 0 || Date.now() < AutoAcceptParty.players[stripRank(p1)]) {
                ChatLib.chat("§6§l[BZA] §b已帮您自动接受来自 " + p1 + " 的队伍邀请");
                ChatLib.command(`p accept ${p1}`);
                delete AutoAcceptParty.players[p1];
                return true;
            }
        }
    }
    return false;
}

//Auto Accept Reparty
register("chat", (player) => {
    AutoAcceptParty.add(stripRank(player),2);
}).setCriteria(/^To (.+): [!！][ ]?p(arty)?(.*)?$/i)

register("chat", (player) => {
    if(eventSettings.AutoAcceptReparty) AutoAcceptParty.add(stripRank(player),120);
}).setCriteria(/(.+)( has disbanded the party!|解散了组队！)/i)

register("chat", (rank,player1,message,player2) => {
    if(!acceptparty(player1) && !/(their|其)/.test(player2)) acceptparty(stripRank(player2).replace(/('s|的)/,""));
}).setCriteria(/------------------------------------------------------>newLine<-(\[[\w+\+-]+] )?([0-9a-zA-Z_]{2,24})( has invited you to join | has invited all members of .+ to |邀请你加入|已邀请.+中的所有成员加入)(.+)( party!|组队！)->newLine<-(You have 60 seconds to accept. Click here to join!|你有60秒时间接受。点击这里以加入！)->newLine<------------------------------------------------------/i)

//p warp 自动二次确认
register("chat",()=>{
    if(!eventSettings.DoubleWarp) return;
    setTimeout(() => {
        ChatLib.command(`p warp`);
    }, 500);    
}).setChatCriteria("Some players are still in-game, run the command again to confirm warp!")

//party transfer
const ptTab = {
    loading : false,
    counter : 0,
    timestamp : 0,
    pl : [],
    partylist : [],
    tabCompletion (cmd) {
        if(this.partylist.length == 0) return;
        let cmdArray = cmd.split(' ');
        if(this.pl.length == 0) this.pl = this.partylist.filter(e => e.toLowerCase().startsWith(cmdArray[1].toLowerCase()) && e != Player.getName());
        if(this.pl.length == 0) return;
        Client.setCurrentChatMessage(cmdArray[0] + " " + this.pl[this.counter]);
        let tabMessage = this.pl.slice();
        tabMessage[this.counter] = "§f" + tabMessage[this.counter] + "§7";
        new Message("§7" + tabMessage.join(', ')).setChatLineId(MessageID.TabCompletion).chat();
        clearTabCompletionMessage.clearNext();
        if(++this.counter >= this.pl.length) this.counter = 0;
    }
}

register("guiKey", (char,key,gui,event) => {
    if(!eventSettings.PTCMD) return;
    if(!Client.isInChat()) return;
    if(key != Keyboard.KEY_TAB) {ptTab.counter = 0;ptTab.pl = [];return;}
    if(ptTab.loading) return;
    let cmd = Client.getCurrentChatMessage();
    if(!cmd.startsWith("/pt ")) return;
    if(Date.now() - ptTab.timestamp > 2 * 60 * 1000 || ptTab.partylist.length == 0) {
        Client.setCurrentChatMessage(cmd + "loading party list");
        ptTab.timestamp = Date.now();
        ptTab.loading = true;
        partylist.get((party) => {
            let players = Object.keys(party);
            if(players.length > 1) {
                try {
                    ptTab.partylist = [];
                    players.forEach((p) => {
                        if(p != Player.getUUID()) {
                            let playername = JSON.parse(FileLib.getUrlContent(`https://sessionserver.mojang.com/session/minecraft/profile/${p}`)).name;
                            if(playername) ptTab.partylist.push(playername);
                        }
                    })
                    ptTab.tabCompletion(cmd);
                    ptTab.loading = false;
                } catch (error) {
                    console.log(error);
                }
            }
        })
        setTimeout(() => { ptTab.loading = false; }, 1000);
    } else ptTab.tabCompletion(cmd);
})

const PTCMDTrigger = register("command",(...player)=>{
    if(!eventSettings.PTCMD) {
        ChatLib.command('pt ' + player.join(' '));
        return;
    } 
    if(player.length == 1) ChatLib.command('party transfer ' + player[0]);
    else ChatLib.command('pt ' + player.join(' '));
}).setCommandName('partytransfer').setAliases('pt').unregister();

register("step", () => {
    if(eventSettings.PTCMD) PTCMDTrigger.register();
    else PTCMDTrigger.unregister();
}).setDelay(10)

//joininstance
export function joininstance(instance,floor) {
    let cmd = "joininstance ";
    switch (instance.toLowerCase()) {
        case "f":
            cmd+= "CATACOMBS_";
            break;
        case "m":
            cmd+= "MASTER_CATACOMBS_";
        break;
        case "t":
            cmd+= "KUUDRA_";
            break;
    }
    if(instance.toLowerCase() == "t") switch (floor.toLowerCase()) {
        case "1":
            cmd+= "NORMAL";
            break;
        case "2":
            cmd+= "HOT";
            break;
        case "3":
            cmd+= "BURNING";
            break;
        case "4":
            cmd+= "FIERY";
            break;
        case "5":
            cmd+= "INFERNAL";
            break;
    } else switch (floor.toLowerCase()) {
        case "e":
        case "0":
            cmd+= "ENTRANCE";
            break;
        case "1":
            cmd+= "FLOOR_ONE";
            break;
        case "2":
            cmd+= "FLOOR_TWO";
            break;
        case "3":
            cmd+= "FLOOR_THREE";
            break;
        case "4":
            cmd+= "FLOOR_FOUR";
            break;
        case "5":
            cmd+= "FLOOR_FIVE";
            break;
        case "6":
            cmd+= "FLOOR_SIX";
            break;
        case "7":
            cmd+= "FLOOR_SEVEN";
            break;
    }
    return cmd;
}

//队伍聊天指令
let nextPartyCommand = "";
let warpDelay = 0;

function RunPartyCommand(partyInfo) {
    if(nextPartyCommand && partyInfo[Player.getUUID()] == "LEADER") {
        if(nextPartyCommand == "p warp" && eventSettings.PartyWarpDelay) {
            warpDelay = Date.now() + eventSettings.PartyWarpDelay * 1000;
            ChatLib.command(`pc ${eventSettings.PartyWarpMessage.replace("%delay%",eventSettings.PartyWarpDelay)}`);
        } else {
            ChatLib.command(nextPartyCommand);
            ChatLib.chat("§6§l[BZA] §b正在执行指令§7: §a/" + nextPartyCommand);
        }
        nextPartyCommand = "";
    }
}

register("step", () => {
    if(eventSettings.PartyWarpDelay && warpDelay && warpDelay < Date.now()) {
        warpDelay = 0;
        ChatLib.command("p warp");
        ChatLib.chat("§6§l[BZA] §b正在执行指令§7: §a/p warp");
    }
}).setDelay(1)

const RegExps = {
    pt : /^[!！][ ]?pt[ ]?(me)?$/i,
    allinvite : /^[!！][ ]?all(inv)?(ite)?$/i,
    pinvite : /^[!！][ ]?p ([a-zA-Z0-9_-]+)$/i,
    warp : /^[!！][ ]?warp?$/i,
    warpcancel : /^[!！][ ]?(warp)?[ ]?c(ancel)?$/i,
    join : /^[!！][ ]?(join)?[ ]?([fmt])([e0-7])$/i,
    sendCoords : /^[!！][ ]?(s)?(end)?[ ]?c(oord|oords)?$/i,
}
register("chat", (party,rank,player,sign,message) => {
    switch (true) {
        case (
            RegExps.pt.test(message) && (eventSettings.PartyTransfer || 
            (  //兼顾一下冰洞的自动转队长,就不用重新写了
                settings.GlaciteMineshaftWarp >= 3 && location.inSkyblock && 
                (
                    location.island == "Mineshaft" || (location.island == "Dwarven Mines" && 
                    (location.location == "Dwarven Base Camp" || location.location == "Glacite Tunnels" || location.location == "Great Glacite Lake"))
                )
            )) && player != Player.getName()
        ):
            nextPartyCommand = "p transfer " + player;
            break;
        case (eventSettings.PartyAllinvite && RegExps.allinvite.test(message)):
            nextPartyCommand = "p settings allinvite";
            break;
        case (eventSettings.PartyInvite && RegExps.pinvite.test(message)):
            nextPartyCommand = "p invite " + RegExps.pinvite.exec(message)[1];
            break;
        case (eventSettings.PartyWarp && RegExps.warp.test(message)):
            nextPartyCommand = "p warp";
            break;
        case (eventSettings.PartyWarp && eventSettings.PartyWarpDelay && RegExps.warpcancel.test(message) && warpDelay > Date.now()):
            nextPartyCommand = `pc ${eventSettings.PartyWarpCancelMessage}`;
            warpDelay = 0;
            break;
        case (eventSettings.PartySkyblockJoin && location.inSkyblock && RegExps.join.test(message)):
            let instance = RegExps.join.exec(message);
            nextPartyCommand = joininstance(instance[2],instance[3]);
            break;
        case (eventSettings.PartySkyblockSendCoords && location.inSkyblock && RegExps.sendCoords.test(message)):
            if(player == Player.getName()) return;
            if(TabList.getNames().filter(name => name.removeFormatting().includes(player)).length == 0) return;
            ChatLib.command(`pc x: ${parseInt(Player.getX())}, y: ${parseInt(Player.getY())}, z: ${parseInt(Player.getZ())}`);
            return;
        default:
            return;
    };
    partylist.get(party => {
        if(player == Player.getName() && partylist.lastGetTime + 30000 > Date.now()) {
            setTimeout(() => {
                RunPartyCommand(party);
            }, 500);
        } else RunPartyCommand(party);
    });
}).setCriteria(/(组队|組隊|Party) > (\[[\w+\+-]+] )?([0-9a-zA-Z_]+)( [♲Ⓑ☀⚒ቾ]+)?: (.+)/i)

register("chat", (player) => {
    if(!eventSettings.DMpartyme || location.server == "") return;
    ChatLib.command("p invite " + stripRank(player));
}).setCriteria(/^From (.+): [!！][ ]?p(arty)?(.*)?$/i)